
//
// 120315 - AH - (Aura *) Created.
// 120504 - AH - Now uses HttpRequestDef. 
// 120619 - AH - (Fantoft *) Took in use VISITOR_NAME HttpRequestParameter.
// 120725 - AH - (Bergen Off. Bibliotek) Now check if named account exists.
//

package org.soekrat.server.servlets.account;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.servlet.FetchParameterResult;
import org.japril.servlet.HttpRequestDef;
import org.soekrat.server.io.db.Account;
import org.soekrat.server.io.db.SoekratDAO;
import org.soekrat.server.io.db.SoekratDAOFactory;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;

/**
 * <p>
 *   Implements request to create new
 *   {@link Account}.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class CreateAccountHttpServlet extends AbstractSoekratHttpServlet 
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public CreateAccountHttpServlet(){}
  
  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
  { 
    HttpRequestDef def=getHttpRequestDef();
    
    if (!hasParameters(req))
    {  
      PrintWriter pw=printSimpleHtmlStart(res);
      pw.println(def.compileApiHtml());
      printSimpleHtmlEnd(pw);
    }
    else
    {
      if (!validate(res, def, req)) return;
      
      FetchParameterResult name=def.fetch(VISITOR_NAME.name(), req);
        
      SoekratDAO dao=new SoekratDAOFactory().create();
      
      String visitor=name.getStringValue();
      
      Account account=dao.getAccount(visitor);
      if (account!=null)
      {
        respond(res, "Account exists");
      }
      else
      {
        account=dao.createAccount(visitor);  
        respond(res, account);
      }
    }
  }
  
  // Specified in AbstractSokratHttpServlet.
  public HttpRequestDef getHttpRequestDef()
  {
    return new HttpRequestDef("/soekrat_server/create_account")
      .desc("Create Account").parameter(VISITOR_NAME);
  }    

}
